﻿using System;
using System.Globalization;
using ContractManagementSystem.BusinessLogicLayer;
using ContractManagementSystem.EntityObjects;

namespace ContractManagementSystem.Presentation.ProfileManagement
{
    public partial class ViewClientDetail : System.Web.UI.Page
    {
        private int _roleId;
        private string _userName;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["RoleId"] != null && Session["UserName"] != null)
            {
                _roleId = int.Parse(Session["RoleId"].ToString(), CultureInfo.InvariantCulture);
                CheckUserPermission();
                DisableTextBox();
                if (!IsPostBack)
                {
                    LoadDataClient();
                }
            }
            else
            {
                Response.Redirect("../LogOn.aspx");
            }
        }
        // when load this page info client not edit 
        protected void DisableTextBox()
        {
            textClientId.Enabled = false;
            textUserName.Enabled = false;
            textFullName.Enabled = false;
            textCompanyName.Enabled = false;
            textAddress.Enabled = false;
            textPhoneNumber.Enabled = false;
            textEmail.Enabled = false;
        }
        //when user click button edit enable textbox allow edit info
        protected void EnableTextBox()
        {
            textClientId.Enabled = false;
            textUserName.Enabled = false;
            textFullName.Enabled = false;
            textCompanyName.Enabled = true;
            textCompanyName.CssClass = "CPFInputField cpfdetailText";
            textAddress.Enabled = true;
            textAddress.CssClass = "CPFInputField cpfdetailText";
            textPhoneNumber.Enabled = true;
            textPhoneNumber.CssClass = "CPFInputField cpfdetailText";
            textEmail.Enabled = false;
        }
        //load info client by role
        protected void LoadDataClient()
        {
            _roleId = int.Parse(Session["RoleId"].ToString(), CultureInfo.InvariantCulture);
            _userName = Session["UserName"].ToString();
            
            if(_roleId==1)
            {
                ButtonEdit.Visible = false;
                ButtonSave.Visible = false;
                LoadUpdateClient();
            }
            else if(_roleId==3)
            {
                LoadClientInfo();
            }
        }
        //load info client when singin by role admin
        private void LoadUpdateClient()
        {
            var id = Request.QueryString["id"];
            if (!string.IsNullOrEmpty(id))
            {
                var dataTable = ClientProfileLogic.SelectClientByClientId(id);
                textClientId.Text = id;
                textUserName.Text = dataTable.Rows[0]["UserName"].ToString();
                textFullName.Text = dataTable.Rows[0]["FullName"].ToString();
                textCompanyName.Text = dataTable.Rows[0]["CompanyName"].ToString();
                textAddress.Text = dataTable.Rows[0]["Address"].ToString();
                textPhoneNumber.Text = dataTable.Rows[0]["PhoneNumber"].ToString();
                textEmail.Text = dataTable.Rows[0]["Email"].ToString();
            }
        }
        //load info client when singin by role client 
        protected void LoadClientInfo()
        {
            var dataTable = ClientProfileLogic.SelectClientByUserName(_userName);
            textClientId.Text = dataTable.Rows[0]["ClientId"].ToString();
            textUserName.Text = dataTable.Rows[0]["UserName"].ToString();
            textFullName.Text = dataTable.Rows[0]["FullName"].ToString();
            textCompanyName.Text = dataTable.Rows[0]["CompanyName"].ToString();
            textAddress.Text = dataTable.Rows[0]["Address"].ToString();
            textPhoneNumber.Text = dataTable.Rows[0]["PhoneNumber"].ToString();
            textEmail.Text = dataTable.Rows[0]["Email"].ToString();
        }

        protected void ButtonEditClick(object sender, EventArgs e)
        {
            EnableTextBox();
        }
        protected void ButtonSaveClick(object sender, EventArgs e)
        {
            var client = new ClientEntity
                             {
                                 ClientId = int.Parse(textClientId.Text.Trim(), CultureInfo.InvariantCulture),
                                 FullName = textFullName.Text,
                                 CompanyName = textCompanyName.Text,
                                 Address = textAddress.Text,
                                 PhoneNumber = textPhoneNumber.Text,
                                 Email = textEmail.Text
                             };
            var result = ClientProfileLogic.UpdateClient(client);
            if (result == "Successfully!")
            {
                labelResultMessage.Text = "Update Successfull !";
            }
            else
            {
                var userEventEntity = new EventEntity
                {
                    UserName = CommonLogic.ConvertToString(Session["UserName"]),
                    EventType = (int)EventTypeList.UserEvent,
                    OnDate = DateTime.Now,
                    Description = "User update failed"
                };
                EventTracer.SaveEvents(userEventEntity);
            }
            DisableTextBox();
        }
        // Check user's permissions
        private void CheckUserPermission()
        {
            var userName = CommonLogic.ConvertToString(Session["UserName"]);
            const int functionId = (int)FunctionList.ViewClient;

            var urlToCome = Page.Master.ResolveUrl("Presentation/AuthorizationError.aspx");

            AuthorizationChecker.IsValidAuthorization(userName, functionId, Response, urlToCome);
        }
    }
}
